/**
 * C Implementation: grib_list
 *
 * Description: how to get values using keys.
 * 如何使用键获取值 (?)
 * 
 **/


#include <stdio.h>
#include <assert.h>

#include "eccodes.h"

int sfx_grib_list()
{
    int err = 0;

    char* filename = "d:/sfxData/ECMWF/eccodes_test_data/satellite.grib";

    FILE* in = fopen(filename, "rb");

    // create new handle from a message in a file
    codes_handle* h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);

    //
    long numberOfContributingSpectralBands;
    CODES_CHECK(codes_get_long(h, "numberOfContributingSpectralBands", &numberOfContributingSpectralBands), 0);
    assert(numberOfContributingSpectralBands == 3);

    // Shrink NB (Number of Bands?) to 2 ?
    numberOfContributingSpectralBands = 2;
    CODES_CHECK(codes_set_long(h, "numberOfContributingSpectralBands", numberOfContributingSpectralBands), 0);

    // Expand NB to 9
    numberOfContributingSpectralBands = 9;
    CODES_CHECK(codes_set_long(h, "numberOfContributingSpectralBands", numberOfContributingSpectralBands), 0);

    // get as a long
    CODES_CHECK(codes_get_long(h, "numberOfContributingSpectralBands", &numberOfContributingSpectralBands), 0);
    printf("numberOfContributingSpectralBands = %ld\n", numberOfContributingSpectralBands);

    // get as a long
    size_t count = 0;
    long values[1024];
    CODES_CHECK(codes_get_size(h, "scaledValueOfCentralWaveNumber", &count), 0);
    printf("count = %ld \n", (long)count);
    assert(count < sizeof(values) / sizeof(values[0]));

    size_t size = count;
    CODES_CHECK(codes_get_long_array(h, "scaledValueOfCentralWaveNumber", values, &size), 0);
    assert(size == count);

    for (int i = 0; i < count; i++) {
        printf("scaledValueOfCentralWaveNumber %lu = %ld\n", (unsigned long)i, values[i]);
        if (i == 0) assert(values[i] == 26870);
        if (i == 1) assert(values[i] == 9272);
    }

    for (int i = 0; i < count; i++) {
        values[i] = i + 1000;
    }

    size = count;
    CODES_CHECK(codes_set_long_array(h, "scaledValueOfCentralWaveNumber", values, size), 0);
    assert(size == count);

    // check what we set 
    long new_values[1024];
    CODES_CHECK(codes_get_long_array(h, "scaledValueOfCentralWaveNumber", new_values, &size), 0);
    assert(size == count);

    for (int i = 0; i < count; i++) {
        printf("Now scaledValueOfCentralWaveNumber %lu = %ld\n", (unsigned long)i, new_values[i]);
        assert(new_values[i] == (i + 1000));
    }

    // free memory
    codes_handle_delete(h);
    fclose(in);
    return 0;
}
